package k8s

import (
	"context"
	"regexp"
	"soma-server/common"
	"soma-server/vo"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

type IPodService interface {
	GetPods(req *vo.PodListRequest) ([]string, error) // 获取pod列表
}

type PodService struct {
	ClientSets map[string]*kubernetes.Clientset
}

func NewPodService() IPodService {
	clientSets := make(map[string]*kubernetes.Clientset)
	for k, v := range common.K8sClients.Clients {
		clientset, err := kubernetes.NewForConfig(v)
		if err != nil {
			common.Log.Errorf("NewForConfig Err:", err)
			return &PodService{}
		}
		clientSets[k] = clientset
	}
	podService := &PodService{
		ClientSets: clientSets,
	}
	return podService
}

func (p *PodService) GetPods(req *vo.PodListRequest) ([]string, error) {
	podName := []string{}
	if len(req.Namespace) == 0 {
		req.Namespace = metav1.NamespaceAll
	}

	pods, err := p.ClientSets[req.Env].CoreV1().Pods(req.Namespace).List(context.Background(), metav1.ListOptions{})
	if err != nil {
		return nil, err
	}
	for _, pod := range pods.Items {
		if len(req.PodName) != 0 {
			r, _ := regexp.Compile(".*" + req.PodName + ".*")
			if m := r.MatchString(pod.Name); m {
				podName = append(podName, pod.Name)
			}
		} else {
			podName = append(podName, pod.Name)
		}
	}
	if len(podName) == 0 {
		podName = []string{"no pod found."}
	}
	return podName, nil
}